package com.wei.czz.framework.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wei.czz.framework.admin.dao.UserAccessTokenDao;
import com.wei.czz.framework.admin.entity.UserAccessTokenEntity;
import com.wei.czz.framework.admin.service.UserAccessTokenService;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2025-04-08 21:23:32
 * className: UserAccessTokenServiceImpl
 * version: 1.0
 * description:
 */
@Service("userAccessTokenService")
public class UserAccessTokenServiceImpl extends ServiceImpl<UserAccessTokenDao, UserAccessTokenEntity>
        implements UserAccessTokenService {

    private static final Logger log = LoggerFactory.getLogger(UserAccessTokenServiceImpl.class);

    @Override
    public void saveOrEdit(UserAccessTokenEntity userAccessToken) {
        // 获取操作用户
        Long userId = SecurityUtils.getOrDefaultUserId(CommonEnum.ZERO.getLongValue());
        String username = SecurityUtils.getOrDefaultUsername("系统");
        Date date = new Date();

        if (Objects.isNull(userAccessToken.getId())) {
            // 新增
            userAccessToken.setDeleteStatus(CommonEnum.ZERO.getValue())
                    .setUpdateTime(date)
                    .setUpdateUser(StringUtils.EMPTY)
                    .setUpdateUserId(CommonEnum.ZERO.getLongValue())
                    .setCreateTime(date)
                    .setCreateUser(username)
                    .setCreateUserId(userId);

            int count = baseMapper.insert(userAccessToken);
            log.info("新增用户令牌完成。count={}", count);
        } else {
            // 编辑
            userAccessToken.setUpdateTime(date)
                   .setUpdateUser(username)
                   .setUpdateUserId(userId);

            int count = baseMapper.updateById(userAccessToken);
            log.info("编辑用户令牌完成。count={}", count);
        }

    }

    @Override
    public List<UserAccessTokenEntity> findEffectList(Long userId, Integer channel) {
        if (Objects.isNull(userId)) {
            log.info("获取用户有效访问令牌列表，传递的用户主键为空");
            return Collections.emptyList();
        }

        LambdaQueryWrapper<UserAccessTokenEntity> userAccessTokenLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userAccessTokenLambdaQueryWrapper.eq(UserAccessTokenEntity::getUserId, userId)
                .eq(Objects.nonNull(channel), UserAccessTokenEntity::getChannel, channel)
                .gt(UserAccessTokenEntity::getRefreshExpireTime, System.currentTimeMillis())
                .eq(UserAccessTokenEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<UserAccessTokenEntity> userAccessTokenList = baseMapper.selectList(userAccessTokenLambdaQueryWrapper);
        log.info("查询用户有效访问令牌完成。list.size={}", userAccessTokenList.size());

        return userAccessTokenList;
    }

    @Override
    public void clearOther(Long userId, Integer channel, String refreshToken) {
        // 获取操作用户
        Long optUserId = SecurityUtils.getOrDefaultUserId(CommonEnum.ZERO.getLongValue());
        String optUsername = SecurityUtils.getOrDefaultUsername("系统");
        Date date = new Date();

        LambdaUpdateWrapper<UserAccessTokenEntity> userAccessTokenLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userAccessTokenLambdaUpdateWrapper.set(UserAccessTokenEntity::getAccessExpireTime, date.getTime())
                .set(UserAccessTokenEntity::getRefreshExpireTime, date.getTime())
                .set(UserAccessTokenEntity::getUpdateTime, date)
                .set(UserAccessTokenEntity::getUpdateUser, optUsername)
                .set(UserAccessTokenEntity::getUpdateUserId, optUserId);
        userAccessTokenLambdaUpdateWrapper.eq(UserAccessTokenEntity::getUserId, userId)
                .eq(UserAccessTokenEntity::getChannel, channel)
                .gt(UserAccessTokenEntity::getRefreshExpireTime, date.getTime())
                .ne(StringUtils.isNotBlank(refreshToken), UserAccessTokenEntity::getRefreshToken, refreshToken)
                .eq(UserAccessTokenEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 更新
        int count = baseMapper.update(userAccessTokenLambdaUpdateWrapper);
        log.info("清除其他令牌完成。count={}", count);

    }
}